// pages/databaseGuide/databaseGuide.js

const app = getApp()

Page({
  
  data: {
    applyorgFlag: true
  },

  onLoad: function (options) {
    wx.showLoading({
      title: '正在加载中',
    })

    let that = this;
    this.onGetOpenid();
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
              console.info("用户信息为：" + JSON.stringify(res.userInfo, null, 2));
              app.globalData.nickName = res.userInfo.nickName
              app.globalData.avatarUrl = res.userInfo.avatarUrl
              app.globalData.hignavatarUrl = app.globalData.avatarUrl.replace(/132/g, '0')
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                nickName: res.userInfo.nickName,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })

    var userorgdata = JSON.parse(options.userorgdata);
    that.userorgdata = userorgdata
    console.log("加载用户群组信息:" + JSON.stringify(userorgdata, null, 2));
    var orgdataid = userorgdata.orgdataid;
    if (orgdataid == null || orgdataid == '' || orgdataid == 'undefined' || orgdataid == undefined){
      orgdataid = userorgdata._id
      this.setData({
        userorgdatadetail: userorgdata
      })
    }else{
      this.setData({
        userorgdatadetail: userorgdata.orgdata
      })
    }
   
    if (app.globalData.openid == null){
      that.setData({
        applyorgFlag: false
      })
    }

    //查询用户是否加入群组
    const db = wx.cloud.database()
    db.collection('USERORG').where({
      _openid: app.globalData.openid,
      applystatus: '1',
      orgid: orgdataid
    }).count({
      success: function (res) {
        console.log("查询用户是否加入群组" + res.total);
        that.data.totalcount = res.total;
        var f = that.data.totalcount > 0;
        var a = that.data.totalcount < 1
        console.log("查询用户是否加入群组" + f);
        if (a) {
          that.setData({
            applyorgFlag: false,
            userorginfodata: ''
          })
          wx.hideLoading()
        }else{
          //查询群组打卡情况
          console.log("查询群组的打卡记录：" + orgdataid)
          console.log("是否开始查询群组信息ing：" + f);
          if (f) {
            db.collection('USERORGINFO').where({
              orgdataid: orgdataid
            }).orderBy('currenttime', 'desc').get({
              success: res => {
                console.log('[数据库] [查询记录] 成功: ', res)
                that.setData({
                  userorginfodata: res.data
                })

              },
              fail: err => {
                wx.showToast({
                  icon: 'none',
                  title: '查询记录失败'
                })
                console.error('[数据库] [查询记录] 失败：', err)
              }
            })
            wx.hideLoading()
          } else {
            that.setData({
              userorginfodata: ''
            })
            wx.hideLoading()
          }
        }
      }
    })
  },

  AppThisOrg: function (e) {

    if (app.globalData.nickName == null) {
      wx.navigateTo({
        url: '../login/login',
      })
      return;
    }

    var odata = e.currentTarget.dataset.id
    console.log("报名参数：" + e.currentTarget.dataset.id.title)

    var nickName = app.globalData.nickName;
    var date = new Date();
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '  ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    const db = wx.cloud.database()
    db.collection('USERORG').add({
      data: {
        nickName: nickName,
        avatarurl: app.globalData.avatarUrl,
        orgid: odata._id,
        addtime: Y + M + D + h + m + s,
        applystatus: odata.authflag,
        orgdata: odata
      },
      success: res => {
        if (odata.authflag == '0'){
          wx.reLaunch({
            url: '../msg/msg_auth',
          })
        }else{
          wx.reLaunch({
            url: '../msg/msg_success',
          })
        }
        
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
      },
      fail: err => {
        wx.reLaunch({
          url: '../msg/msg_fail',
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },

  onShareAppMessage: function () {
    let that = this;
    console.log("报名参数：" + that.userorgdata)
    var userorgdata = JSON.stringify(that.userorgdata);
    if (app.globalData.nickName == null) {
      wx.navigateTo({
        url: '../login/login',
      })
      return;
    }
    return {
      title: app.globalData.nickName + "邀请您在" + that.userorgdata.title + "打卡",
      imageUrl: that.userorgdata.headurl,
      path: "/pages/userorgdetail/userorgdetail?userorgdata=" + userorgdata
    }
  },

  ClickThisOrg : function (e) {
    var userclickdata = JSON.stringify(e.currentTarget.dataset.id)
    console.log("跳转进入打卡页面参数:" + userclickdata);
    wx.navigateTo({
      url: '../userorginfoadd/userorginfoadd?userclickdata=' + userclickdata,
    })
  },

  onQuery: function (e) {
    const db = wx.cloud.database()
    //查询当前用户所有的 counters
    db.collection('PVERSION').where({
        version: 2019
    }).orderBy('time', 'desc').get({
      success: res => {
        this.setData({
          queryResult: res.data
        })
        console.log('[数据库] [查询记录] 成功: ', res)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },

  onGetOpenid: function () {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        var _openid = res.result.openid
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },

  goHome: function() {
    const pages = getCurrentPages()
    if (pages.length === 2) {
      wx.navigateBack()
    } else if (pages.length === 1) {
      wx.redirectTo({
        url: '../index/index',
      })
    } else {
      wx.reLaunch({
        url: '../index/index',
      })
    }
  }
})